package com.ycsj.goldmedalnewconcept.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.App;
import com.ycsj.goldmedalnewconcept.DemoContext;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtils;

import java.util.Locale;

import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationFragment;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

/**
 * Created by Bob on 15/8/18.
 * 会话页面
 */
@SuppressLint({ "NewApi", "DefaultLocale" })
public class ConversationActivity extends BaseJpStarActivity {

    private TextView mTitle;
    private RelativeLayout mBack;

    private String mTargetId;
    private String  mTargetName;
    private String role;
    /**
     * 刚刚创建完讨论组后获得讨论组的id 为targetIds，需要根据 为targetIds 获取 targetId
     */
    private String mTargetIds;

    /**
     * 会话类型
     */
    private Conversation.ConversationType mConversationType;
	private ImageView img2;
	
	private String conversationId;
	private String targetId;
	private String Id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.conversation);
        Intent intent = getIntent();

        SystemBarTintManager tintManager = new SystemBarTintManager(this);
		tintManager.setStatusBarTintEnabled(true);
		tintManager.setStatusBarTintResource(R.color.base_color);
        
		
        setActionBar();

        getIntentDate(intent);

        isReconnect(intent);
    }

    /**
     * 展示如何从 Intent 中得到 融云会话页面传递的 Uri
     */
    private void getIntentDate(Intent intent) {

        mTargetId = getIntent().getData().getQueryParameter("targetId");
        
        mTargetIds = getIntent().getData().getQueryParameter("targetIds");

        mTargetName = intent.getData().getQueryParameter("title");
        String nn = getIntent().getData().getQueryParameter("title");
        //intent.getData().getLastPathSegment();//获得当前会话类型
        mConversationType = Conversation.ConversationType.valueOf(intent.getData().getLastPathSegment().toUpperCase(Locale.getDefault()));
        
        Log.e("TEST", "mTargetId"+mTargetId);
        Log.e("TEST", "mTargetIds"+mTargetIds);
        Log.e("TEST", "mTargetName"+mTargetName);
        
        
        
        enterFragment(mConversationType, mTargetId);
       
//      setActionBarTitle(SPUtils.getString(ConversationActivity.this, "tagetUsername"));
        setActionBarTitle(nn);
        
        
    }


    /**
     * 加载会话页面 ConversationFragment
     *
     * @param mConversationType
     * @param mTargetId
     */
    @SuppressLint("NewApi")
	private void enterFragment(Conversation.ConversationType mConversationType, String mTargetId) {

        ConversationFragment fragment = (ConversationFragment) getSupportFragmentManager().findFragmentById(R.id.conversation);

        Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
                .appendPath("conversation").appendPath(mConversationType.getName().toLowerCase())
                .appendQueryParameter("targetId", mTargetId).build();

        
        fragment.setUri(uri);
        
        
        conversationId=mTargetId;
     
//        Log.e("word", ""+uri);
    }


    /**
     * 判断消息是否是 push 消息
     */
    private void isReconnect(Intent intent) {


        String token = null;

        if (DemoContext.getInstance() != null) {
        	token="JrklokjgQ33UhlASobCWuy75KxfWYG+yQTUevpxn5RVnTJFeDFjtvBe92xD34Wn/5Uo9+INLosxSMiMuUdsU7AF9DuwCOvHn";
           // token = DemoContext.getInstance().getSharedPreferences().getString("DEMO_TOKEN", "default");
        }

        //push或通知过来
        if (intent != null && intent.getData() != null && intent.getData().getScheme().equals("rong")) {

            //通过intent.getData().getQueryParameter("push") 为true，判断是否是push消息
            if (intent.getData().getQueryParameter("push") != null
                    && intent.getData().getQueryParameter("push").equals("true")) {

                reconnect(token);
            } else {
                //程序切到后台，收到消息后点击进入,会执行这里
                if (RongIM.getInstance() == null || RongIM.getInstance().getRongIMClient() == null) {

                    reconnect(token);
                } else {
                    enterFragment(mConversationType, mTargetId);
                }
            }
        }
    }

    /**
     * 设置 actionbar 事件
     */
    private void setActionBar() {

        mTitle = (TextView) findViewById(R.id.tv_title);
        
        img2 = (ImageView) findViewById(R.id.img2);
        Id = getIntent().getData().getQueryParameter("targetId");
        
//        if(SPUtils.getString(ConversationActivity.this, "onUserPortraitClickid").length()==11){
//        	Picasso.with(ConversationActivity.this).load(R.drawable.personalset).into(img2);
//        	img2.setVisibility(View.VISIBLE);
//        }else{
//        	img2.setVisibility(View.VISIBLE);
//        	Picasso.with(ConversationActivity.this).load(R.drawable.double_personalset).into(img2);
//        }
        if(Id.length()<13){
        	Picasso.with(ConversationActivity.this).load(R.drawable.personalset).into(img2);
        	img2.setVisibility(View.VISIBLE);
        }else{
        	img2.setVisibility(View.VISIBLE);
        	Picasso.with(ConversationActivity.this).load(R.drawable.double_personalset).into(img2);
        }
        mBack = (RelativeLayout) findViewById(R.id.rl_back);

        mBack.setOnClickListener(new View.OnClickListener() {
            @Override 
            public void onClick(View v) {
                finish();
            }
        });
        
        img2.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) { 
				if(Id.length()==12){
					SPUtils.put(ConversationActivity.this, "clickUserid", mTargetId.substring(0, 11));
					SPUtils.put(ConversationActivity.this, "clickRole", mTargetId.substring(11, 12));
					if("0".equals(mTargetId.substring(11, 12))){
						Intent intent = new Intent(ConversationActivity.this,MineConversationInfo.class);
						//intent.putExtra("userInfo", SPUtils.getString(ConversationActivity.this, "onUserPortraitClickid"));
						intent.putExtra("userInfo", mTargetId);
						
						
//						Toast.makeText(ConversationActivity.this, SPUtils.getString(ConversationActivity.this, "tagetUserid"), 0).show();
						startActivity(intent);
					}else{
						Intent intent = new Intent(ConversationActivity.this,UserInfoActivity.class);
						intent.putExtra("c", mTargetId.substring(0, 11));
						intent.putExtra("role",SPUtil.getString(ConversationActivity.this, "clickRole", ""));
						Log.e("role", SPUtil.getString(ConversationActivity.this, "clickRole", ""));
						startActivity(intent);
					}
				}else if(Id.length()==11){
//				Intent intent = new Intent(ConversationActivity.this,MineConversationInfo.class);
//				//intent.putExtra("userInfo", SPUtils.getString(ConversationActivity.this, "onUserPortraitClickid"));
//				intent.putExtra("userInfo", mTargetId);
//				SPUtils.put(ConversationActivity.this, "clickUserid", mTargetId.substring(0, 11));
//				SPUtils.put(ConversationActivity.this, "clickRole", mTargetId.substring(11, 12));
//				
////				Toast.makeText(ConversationActivity.this, SPUtils.getString(ConversationActivity.this, "tagetUserid"), 0).show();
//				startActivity(intent);
					
					
					if("0".equals(SPUtil.getString(ConversationActivity.this, "clickRole", ""))){
						Intent intent = new Intent(ConversationActivity.this,MineConversationInfo.class);
						//intent.putExtra("userInfo", SPUtils.getString(ConversationActivity.this, "onUserPortraitClickid"));
						intent.putExtra("userInfo", mTargetId);
						
						startActivity(intent);
					}else{
						
						
						Intent intent = new Intent(ConversationActivity.this,UserInfoActivity.class);
						intent.putExtra("c", mTargetId);
						intent.putExtra("role", SPUtil.getString(ConversationActivity.this, "clickRole", ""));
//						Log.e("role", SPUtil.getString(ConversationActivity.this, "clickRole", ""));
						startActivity(intent);
					}
				  }
//				else if("0".equals(mTargetId.substring(11, 12))){
//					  
//							Intent intent1 = new Intent(ConversationActivity.this,MineConversationInfo.class);
//							SPUtils.put(ConversationActivity.this, "clickUserid", mTargetId.substring(0, 11));
//							SPUtils.put(ConversationActivity.this, "clickRole", mTargetId.substring(11, 12));
//							intent1.putExtra("userInfo", mTargetId);
//							startActivity(intent1);
//					  
//				  }
				  else{
					  
					  Intent intent = new Intent(ConversationActivity.this,GroupConversationInfoActivity.class);
						intent.putExtra("GroupId",Id );
						SPUtils.put(ConversationActivity.this, "clickGroupid", mTargetId);
						
						startActivity(intent);
				  }
			}
		});
        
        
    }



    /**
     * 设置 actionbar title
     */
    private void setActionBarTitle(String targetid) {

        mTitle.setText(targetid);
    }

    /**
     * 重连
     *
     * @param token
     */
    @SuppressLint("NewApi")
	private void reconnect(String token) {

        if (getApplicationInfo().packageName.equals(App.getCurProcessName(getApplicationContext()))) {

            RongIM.connect(token, new RongIMClient.ConnectCallback() {
                @Override
                public void onTokenIncorrect() {

                }

                @Override
                public void onSuccess(String s) {

                    enterFragment(mConversationType, mTargetId);
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {

                }
            });
        }
    }
}
